package com.itjoin.pro_netty.ch1_3_2.server;

import com.alibaba.fastjson.JSONObject;
import com.itjoin.pro_netty.asyn.RequestFuture;
import com.itjoin.pro_netty.asyn.Response;
import com.itjoin.pro_netty.core.Mediator;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

//Sharable注解表示此Handler对所有Channel共享，无状态，注意多线程并发
@ChannelHandler.Sharable
public class ServerHandler extends ChannelInboundHandlerAdapter {
    /**
     * 读取客户端发送的数据
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        //获取客户端发送的请求，并转换成RequestFuture对象，
        //由于经过StringDecoder解码器，因此msg为String类型
        RequestFuture request = JSONObject.parseObject(msg.toString(), RequestFuture.class);
        //获取请求id
        long id = request.getId();
        System.out.println("请求信息为===" + msg.toString());
        //构建响应结果
        Response response = new Response();
        response.setId(id);
        response.setResult("服务器响应ok" + id);
        //把响应结果返回给客户端
        ctx.channel().writeAndFlush(JSONObject.toJSONString(response));
    }
}
